<?php
/**
 * Created by PhpStorm.
 * User: Yangxufeng
 * Date: 2018-09-21
 * Time: 10:47
 */

namespace app\index\server;

use app\index\model\Order as OrderModel;
use app\lib\exception\DatabaseException;
use think\Db;

class OrderServer extends BaseServer
{
	// 获取用户的所有订单
	public function getOrderList($user_id, $status, $page, $count)
	{
		if (!$count) {
			$count = 6;
		}
		try {
			$offset = $page * $count - 1;
			if ($offset < 0) {
				$offset = 0;
			}
		//	$order_list = OrderModel::where('user_id', '=', $user_id)
		//		->where('status', $status)
		//		->order('id', 'desc')
		//		->limit($offset, $count)
		//		->select();a
		$order_list = OrderModel::with(['product'])
			    ->where('user_id', '=', $user_id)
				->where('status', $status)
				->order('id', 'desc')
				->limit($offset, $count)
				->select();
			if (!$order_list) {
				return redirect('order/empty');
			}
		} catch (Exception $e) {
			throw new DatabaseException([
				'errorCode' => 50001,
				'msg' => '非常抱歉,系统发生错误请联系管理员,谢谢您的配合'
			]);
		}
		return $order_list;
	}

	public function deleteOne($condition)
	{
		try {
			$result = OrderModel::where($condition)
				->delete();
		} catch (Exception $e) {
			throw new DatabaseException([
				'errorCode' => 50001,
				'msg' => '非常抱歉,系统发生错误请联系管理员,谢谢您的配合'
			]);
		}
		return $result;
	}

	/**
	 * @var 订单生成
	 */
	public function insertOrder($order, $info)
	{
		Db::startTrans();
		try {
			$result = Db::table('sy_order')->insertGetId($order);
			$info['order_id'] = $result;
			$result = Db::table('sy_order_product')->insertGetId($info);
			OrderModel::commit();
		} catch (Exception $e) {
			OrderModel::rollback();
			throw new DatabaseException([
				'errorCode' => 50001,
				'msg' => '非常抱歉,系统发生错误请联系管理员,谢谢您的配合'
			]);
		}
		return $result;
	}

}
